<?php

namespace App\Admin\Actions\ShopUser;

use App\Admin\AdminUpload;
use App\Library\Logic\AmountLogic;
use App\Library\Logic\OperateLogLogic;
use App\Models\AdjustmentModel;
use App\Models\ShopUserModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class ShopUserAdjustmentAction extends RowAction
{
    public $name = '调账';

    public function handle(ShopUserModel $model, Request $request): Response
    {
        if (is_null($model)) return $this->response()->error(__('errorCode.433'))->refresh();
        else if ((int)$model->user_status === 2) return $this->response()->error('用户已被封禁')->refresh();
        else if ($request->password !== config('app.adjustmentPassword')) {
            return $this->response()->error('密码错误')->refresh();
        }
        foreach ($request->file as $v) $arr[] = AdminUpload::upload($v)->serial_number;

        $adjustment = AdjustmentModel::insertForModel([
            'type' => 1,
            'userId' => $model->user_id,
            'amount' => (float)$request->adjustment_amount,
            'operateId' => Admin::user()->user_id,
            'fileIds' => !empty($arr) ? $arr : []
        ]);
        AmountLogic::insertForModelOfLock([
            'type' => 'user_adjustment',
            'userId' => $adjustment->user_id,
            'title' => '用户充值',
            'object_type' => 'user_adjustment',
            'object_id' => $adjustment->id,
            'amount' => $adjustment->amount,
            'description' => $adjustment->description,
        ]);
        OperateLogLogic::add(Admin::user()->user_id, 'admin.user.amount.adjust');
        return $this->response()->success('操作成功')->refresh();
    }

    public function form(): void
    {
        $this->text('adjustment_amount', '调账金额')->rules(['required', 'min:0.01', 'regex:' . __('com.priceReg')]);
        $this->multipleImage('file', '凭证')->required();
        $this->password('password', '密码')->attribute('maxlength', 10)->required();
    }
}
